<template>
  <Header />
  <div class="checkout-view">
    <div class="checkout-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>订单结算</h1>
        <div class="step-indicator">
          <div class="step active">1. 确认订单</div>
          <div class="step-line"></div>
          <div class="step">2. 选择地址</div>
          <div class="step-line"></div>
          <div class="step">3. 支付</div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        加载中...
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error && isLoggedIn" class="error-message">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ errorMessage }}</div>
        <div v-if="debugInfo" class="debug-info">
          <h4>调试信息:</h4>
          <pre>{{ debugInfo }}</pre>
        </div>
        <button class="retry-btn" @click="initCheckout">重试</button>
      </div>

      <!-- 结算内容 -->
      <div v-else class="checkout-content">
        <!-- 订单商品列表 -->
        <div class="order-items">
          <h2>订单商品</h2>
          <div class="item" v-for="item in orderItems" :key="item.cartId">
            <div class="item-image">
              <img :src="item.productImg || '/src/assets/product-default.png'" :alt="item.productName">
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.productName }}</div>
              <div class="item-spec">{{ item.specification || '默认规格' }}</div>
            </div>
            <div class="item-price">¥{{ item.sellingPrice.toFixed(2) }}</div>
            <div class="item-quantity">x{{ item.quantity }}</div>
            <div class="item-total">¥{{ (item.sellingPrice * item.quantity).toFixed(2) }}</div>
          </div>
        </div>

        <!-- 收货地址 -->
        <div class="address-section">
          <h2>收货地址</h2>
          <div v-if="addresses.length === 0" class="no-address">
            <p>您还没有添加收货地址</p>
          </div>
          <div v-else class="address-list">
            <div v-for="address in addresses" :key="address.shippingId" class="address-item"
              :class="{ active: String(selectedAddress?.shippingId) === String(address.shippingId) }" @click="selectAddress(address)">
              <div class="address-info">
                <div class="contact">
                  <span class="name">{{ address.receiverName }}</span>
                  <span class="phone">{{ address.receiverPhone }}</span>
                </div>
                <div class="address-detail">
                  {{ address.receiverProvince }} {{ address.receiverCity }} {{ address.receiverDistrict }} {{
                    address.receiverAddress }}
                </div>
              </div>
              <div class="address-actions">
                <button class="edit-btn" @click.stop="editAddress(address)">编辑</button>
                <button class="delete-btn" @click.stop="deleteAddress(address.shippingId)">删除</button>
              </div>
            </div>

          </div>
        </div>

        <!-- 地址选择弹窗 -->
        <div v-if="showAddressModal" class="modal-overlay" @click="showAddressModal = false">
          <div class="modal-content" @click.stop>
            <div class="modal-header">
              <h3>选择收货地址</h3>
              <button class="close-btn" @click="showAddressModal = false">×</button>
            </div>
            <div class="modal-body">
              <div v-if="allAddresses.length === 0" class="no-addresses">
                <p>您还没有添加任何收货地址</p>
              </div>
              <div v-else class="address-selection">
                <div class="selection-tip">
                  <p>请选择一个收货地址，选中的地址将添加到订单中</p>
                </div>
                <div v-for="address in allAddresses" :key="address.shippingId" class="address-option" :class="{
                  active: String(selectedAddress?.shippingId) === String(address.shippingId),
                  'already-in-checkout': isAddressInCheckout(address.shippingId)
                }" @click="selectAddressFromModal(address)">
                  <div class="address-content">
                    <div class="contact">
                      <span class="name">{{ address.receiverName }}</span>
                      <span class="phone">{{ address.receiverPhone }}</span>
                    </div>
                    <div class="address-detail">
                      {{ address.receiverProvince }} {{ address.receiverCity }} {{ address.receiverDistrict }} {{
                        address.receiverAddress }}
                    </div>
                  </div>
                  <div class="address-status">
                    <span v-if="isAddressInCheckout(address.shippingId)" class="in-checkout">已在订单中</span>
                    <span v-else-if="String(selectedAddress?.shippingId) === String(address.shippingId)" class="selected">当前选择</span>
                    <span v-else class="available">点击选择</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button class="cancel-btn" @click="showAddressModal = false">取消</button>
              <button class="confirm-btn" @click="confirmAddressSelection" :disabled="!selectedAddress">
                {{ selectedAddress ? '确认选择' : '请先选择地址' }}
              </button>
            </div>
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="payment-section">
          <h2>支付方式</h2>
          <div class="payment-methods">
            <div v-for="method in paymentMethods" :key="method.id" class="payment-method"
              :class="{ active: selectedPaymentMethod === method.id }" @click="selectPaymentMethod(method.id)">
              <div class="method-icon">{{ method.icon }}</div>
              <div class="method-name">{{ method.name }}</div>
              <div class="method-desc">{{ method.description }}</div>
            </div>
          </div>
        </div>

        <!-- 订单摘要 -->
        <div class="order-summary">
          <h2>订单摘要</h2>
          <div class="summary-item">
            <span>商品总价：</span>
            <span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>运费：</span>
            <span>¥{{ shippingFee.toFixed(2) }}</span>
          </div>
          <div class="summary-item total">
            <span>应付总额：</span>
            <span class="total-amount">¥{{ (totalPrice + shippingFee).toFixed(2) }}</span>
          </div>
        </div>

        <!-- 提交订单 -->
        <div class="checkout-actions">
          <button class="submit-order-btn" @click="submitOrder" :disabled="!canSubmit">
            提交订单
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '../Header.vue';
import { useStore } from 'vuex';
import { computed, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { createOrder } from '@/api/order';
import { getAddresses } from '@/api/address';
import { deleteCartItem } from '@/api/cart';
import { safeApiCall, getResponseData, isResponseSuccess } from '@/utils/apiHelper';

export default {
  name: 'CheckoutView',
  components: {
    Header
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();

    const loading = ref(false);
    const error = ref(false);
    const errorMessage = ref('');
    const debugInfo = ref('');
    const orderItems = ref([]);
    const addresses = ref([]);
    const selectedAddress = ref(null);
    const selectedPaymentMethod = ref(1);
    const showAddressModal = ref(false);
    const allAddresses = ref([]);

    const currentUser = computed(() => store.state.currentUser);
    const isLoggedIn = computed(() => currentUser.value !== null);

    // 支付方式配置
    const paymentMethods = [
      { id: 1, name: '支付宝', icon: '💰', description: '推荐使用支付宝支付' },
      { id: 2, name: '微信支付', icon: '💳', description: '使用微信扫码支付' },
      { id: 3, name: '银行卡', icon: '🏦', description: '支持各大银行' }
    ];

    // 计算属性
    const totalPrice = computed(() => {
      return orderItems.value.reduce((total, item) => {
        return total + (item.sellingPrice * item.quantity);
      }, 0);
    });

    const shippingFee = computed(() => {
      return totalPrice.value >= 99 ? 0 : 10; // 满99包邮
    });

    const canSubmit = computed(() => {
      return selectedAddress.value && orderItems.value.length > 0;
    });

    // 初始化结算数据
    const initCheckout = async () => {
      loading.value = true;
      error.value = false;
      debugInfo.value = '';

      try {
        // 确保购物车数据已加载
        if (!store.state.cartItems || store.state.cartItems.length === 0) {
          await store.dispatch('fetchCartItems');
        }

        // 获取购物车商品
        const cartItems = store.state.cartItems || [];
        const selectedCartIds = route.query.items;

        console.log('购物车商品:', cartItems);
        console.log('选中的商品ID:', selectedCartIds);

        // 收集调试信息
        const debugData = {
          cartItemsCount: cartItems.length,
          cartItems: cartItems.map(item => ({
            cartId: item.cartId,
            productId: item.productId,
            productName: item.productName,
            selected: item.selected
          })),
          selectedCartIds: selectedCartIds,
          selectedCartIdsType: typeof selectedCartIds,
          selectedCartIdsIsArray: Array.isArray(selectedCartIds),
          routeQuery: route.query,
          currentUser: currentUser.value
        };

        if (selectedCartIds) {
          if (Array.isArray(selectedCartIds)) {
            // 将字符串ID转换为数字进行比较
            const selectedIds = selectedCartIds.map(id => parseInt(id));
            orderItems.value = cartItems.filter(item => selectedIds.includes(item.cartId));
            debugData.selectedIdsConverted = selectedIds;
            debugData.filteredItemsCount = orderItems.value.length;
            console.log('数组ID筛选:', {
              original: selectedCartIds,
              converted: selectedIds,
              result: orderItems.value
            });
          } else {
            // 单个ID的情况
            const selectedId = parseInt(selectedCartIds);
            orderItems.value = cartItems.filter(item => item.cartId === selectedId);
            debugData.selectedIdConverted = selectedId;
            debugData.filteredItemsCount = orderItems.value.length;
            console.log('单个ID筛选:', {
              original: selectedCartIds,
              converted: selectedId,
              result: orderItems.value
            });
          }
        } else {
          // 如果没有指定商品ID，使用选中的商品
          orderItems.value = cartItems.filter(item => item.selected);
          debugData.filteredItemsCount = orderItems.value.length;
          debugData.filterMethod = 'selected';

          // 如果还是没有商品，使用所有购物车商品
          if (orderItems.value.length === 0 && cartItems.length > 0) {
            orderItems.value = cartItems;
            debugData.filterMethod = 'all';
            console.log('使用所有购物车商品进行结算');
          }
        }

        console.log('结算商品:', orderItems.value);

        if (orderItems.value.length === 0) {
          debugInfo.value = JSON.stringify(debugData, null, 2);
          throw new Error('购物车中没有商品，请先添加商品到购物车');
        }

        // 获取收货地址
        const addressResult = await safeApiCall(
          () => getAddresses(currentUser.value.userId),
          '获取地址失败'
        );

        if (addressResult.success) {
          // 处理后端返回的数据结构
          let addressData = [];
          if (Array.isArray(addressResult.data)) {
            // 直接返回数组的情况
            addressData = addressResult.data;
          } else if (addressResult.data && Array.isArray(addressResult.data.addresses)) {
            // 后端返回 {status: 200, addresses: [...]} 的情况
            addressData = addressResult.data.addresses;
          } else if (addressResult.data && addressResult.data.status === 200 && Array.isArray(addressResult.data.addresses)) {
            // 后端返回 {status: 200, addresses: [...]} 的情况
            addressData = addressResult.data.addresses;
          }

          addresses.value = addressData;
          allAddresses.value = [...addressData]; // 复制到allAddresses
          console.log('地址数据加载成功:', {
            addressesCount: addresses.value.length,
            allAddressesCount: allAddresses.value.length,
            addresses: addresses.value,
            allAddresses: allAddresses.value
          });
        } else {
          addresses.value = [];
          allAddresses.value = [];
          console.warn('获取地址失败:', addressResult.message);
        }

        // 默认选择第一个地址
        if (addresses.value.length > 0) {
          selectedAddress.value = addresses.value[0];
        }

      } catch (err) {
        console.error('初始化结算失败:', err);
        error.value = true;
        errorMessage.value = err.message || '初始化结算失败';
      } finally {
        loading.value = false;
      }
    };

    // 选择地址
    const selectAddress = (address) => {
      selectedAddress.value = address;
    };

    // 编辑地址
    const editAddress = (address) => {
      router.push({
        path: '/address',
        query: { edit: address.shippingId }
      });
    };

    // 删除地址
    const deleteAddress = async (shippingId) => {
      if (!confirm('确定要删除这个地址吗？')) return;

      try {
        // 这里需要调用删除地址的API
        addresses.value = addresses.value.filter(addr => addr.shippingId !== shippingId);

        if (selectedAddress.value?.shippingId === shippingId) {
          selectedAddress.value = addresses.value.length > 0 ? addresses.value[0] : null;
        }
      } catch (err) {
        console.error('删除地址失败:', err);
        alert('删除地址失败');
      }
    };

    // 选择支付方式
    const selectPaymentMethod = (methodId) => {
      selectedPaymentMethod.value = methodId;
    };

    // 提交订单
    const submitOrder = async () => {
      if (!canSubmit.value) {
        alert('请选择收货地址');
        return;
      }

      try {
        const orderData = {
          userId: currentUser.value.userId,
          addressId: selectedAddress.value.shippingId,
          paymentMethod: selectedPaymentMethod.value,
          items: orderItems.value.map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            price: item.sellingPrice,
            productName: item.productName,
            productImg: item.productImg,
            specification: item.specification || '默认规格'
          })),
          totalAmount: totalPrice.value + shippingFee.value,
          shippingFee: shippingFee.value
        };

        const result = await safeApiCall(
          () => createOrder(orderData),
          '创建订单失败'
        );

        if (result.success) {
          const orderId = result.data?.orderId || result.data?.id;
          if (orderId) {
            // 下单成功后只删除已下单商品
            for (const item of orderItems.value) {
              if (item.cartId) {
                await deleteCartItem(currentUser.value.userId, item.cartId);
              }
            }
            // 将支付方式字符串转换为数字类型
            const getPaymentTypeNumber = (method) => {
              switch (method) {
                case 'alipay': return 1;
                case 'wechat': return 2;
                case 'bank': return 3;
                default: return 1; // 默认为支付宝
              }
            };
            
            // 立刻发起支付
            const payParams = {
              orderId,
              paymentType: getPaymentTypeNumber(selectedPaymentMethod.value),
              amount: orderData.totalAmount
            };
            console.log('支付参数', payParams);
            if (!payParams.orderId || !payParams.paymentType || !payParams.amount) {
              alert('支付参数不完整，请检查订单号、支付方式、金额');
              return;
            }
            const payResult = await safeApiCall(
              () => require('@/api/order').payOrder(payParams),
              '支付失败'
            );
            if (payResult.success || payResult.status === 200) {
              // 跳转到支付页面
              router.push({
                name: 'Payment',
                params: { orderId: orderId },
                query: {
                  amount: orderData.totalAmount,
                  method: selectedPaymentMethod.value
                }
              });
            } else {
              let msg = payResult.message;
              if (typeof msg === 'object') {
                msg = JSON.stringify(msg);
              }
              alert(msg || '支付失败');
            }
          } else {
            throw new Error('订单创建成功但未返回订单ID');
          }
        } else {
          throw new Error(result.message);
        }
      } catch (err) {
        console.error('提交订单失败:', err);
        alert(err.message || '提交订单失败');
      }
    };

    // 选择地址从弹窗
    const selectAddressFromModal = (address) => {
      selectedAddress.value = address;
    };

    // 确认地址选择
    const confirmAddressSelection = () => {
      if (selectedAddress.value) {
        // 检查地址是否已经在结算页面的地址列表中
        const isAlreadyInCheckout = addresses.value.some(
          addr => String(addr.shippingId) === String(selectedAddress.value.shippingId)
        );

        // 如果不在列表中，添加到结算页面的地址列表
        if (!isAlreadyInCheckout) {
          addresses.value.push(selectedAddress.value);
          console.log('新地址已添加到结算页面:', selectedAddress.value);
        }

        // 更新allAddresses列表，确保数据同步
        const isInAllAddresses = allAddresses.value.some(
          addr => String(addr.shippingId) === String(selectedAddress.value.shippingId)
        );
        if (!isInAllAddresses) {
          allAddresses.value.push(selectedAddress.value);
        }
      }
      showAddressModal.value = false;
    };



    // 检查地址是否在结算页面
    const isAddressInCheckout = (shippingId) => {
      return addresses.value.some(address => String(address.shippingId) === String(shippingId));
    };



    // 加载所有地址
    const loadAllAddresses = async () => {
      try {
        const userId = currentUser.value && currentUser.value.userId;
        console.log('【DEBUG】loadAllAddresses: userId =', userId);
        if (!userId) {
          console.warn('【DEBUG】loadAllAddresses: userId 为空，跳过请求');
          allAddresses.value = [];
          return;
        }

        console.log('【DEBUG】开始调用地址API，userId =', userId);
        console.log('【DEBUG】API URL: /user/address?userId=' + userId);
        
        const addressResult = await safeApiCall(
          () => getAddresses(userId),
          '获取地址失败'
        );
        console.log('【DEBUG】loadAllAddresses: addressResult =', addressResult);

        // 添加原始API调用的调试信息
        try {
          console.log('【DEBUG】尝试直接调用API...');
          const rawResponse = await getAddresses(userId);
          console.log('【DEBUG】原始API响应:', rawResponse);
        } catch (rawError) {
          console.error('【DEBUG】原始API调用失败:', rawError);
          console.error('【DEBUG】原始错误详情:', {
            message: rawError.message,
            status: rawError.response?.status,
            statusText: rawError.response?.statusText,
            data: rawError.response?.data
          });
        }

        if (addressResult.success) {
          // 处理后端返回的数据结构
          let addressData = [];
          console.log('【DEBUG】原始响应数据:', addressResult.data);

          if (Array.isArray(addressResult.data)) {
            // 直接返回数组的情况
            addressData = addressResult.data;
            console.log('【DEBUG】数据是数组格式');
          } else if (addressResult.data && Array.isArray(addressResult.data.addresses)) {
            // 后端返回 {status: 200, addresses: [...]} 的情况
            addressData = addressResult.data.addresses;
            console.log('【DEBUG】数据在addresses字段中');
          } else if (addressResult.data && addressResult.data.status === 200 && Array.isArray(addressResult.data.addresses)) {
            // 后端返回 {status: 200, addresses: [...]} 的情况
            addressData = addressResult.data.addresses;
            console.log('【DEBUG】数据在status=200的addresses字段中');
          } else {
            console.warn('【DEBUG】无法识别的数据格式:', addressResult.data);
          }

          allAddresses.value = addressData;
          console.log('【DEBUG】处理后的地址数据:', {
            count: allAddresses.value.length,
            addresses: allAddresses.value
          });
        } else {
          allAddresses.value = [];
          console.error('【DEBUG】获取地址失败:', {
            success: addressResult.success,
            message: addressResult.message,
            error: addressResult.error
          });
        }
      } catch (err) {
        console.error('【DEBUG】获取所有地址失败:', err);
        allAddresses.value = [];
        throw err; // 重新抛出错误以便上层处理
      }
    };

    // 添加新地址到结算页面
    const addAddressToCheckout = (address) => {
      // 检查地址是否已经存在
      const existingIndex = addresses.value.findIndex(
        addr => String(addr.shippingId) === String(address.shippingId)
      );

      if (existingIndex === -1) {
        // 地址不存在，添加到列表
        addresses.value.push(address);
        console.log('地址已添加到结算页面:', address);
      } else {
        // 地址已存在，更新信息
        addresses.value[existingIndex] = address;
        console.log('地址信息已更新:', address);
      }

      // 如果当前没有选中的地址，自动选择新添加的地址
      if (!selectedAddress.value) {
        selectedAddress.value = address;
      }
    };

    onMounted(() => {
      if (!currentUser.value) {
        router.push('/login');
        return;
      }
      initCheckout();
    });

    return {
      loading,
      error,
      errorMessage,
      debugInfo,
      orderItems,
      addresses,
      selectedAddress,
      selectedPaymentMethod,
      paymentMethods,
      totalPrice,
      shippingFee,
      canSubmit,
      isLoggedIn,
      initCheckout,
      selectAddress,
      editAddress,
      deleteAddress,
      selectPaymentMethod,
      submitOrder,
      showAddressModal,
      allAddresses,
      isAddressInCheckout,
      selectAddressFromModal,
      confirmAddressSelection,
      loadAllAddresses,
      addAddressToCheckout
    };
  }
};
</script>

<style scoped>
.checkout-view {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 2rem 0;
}

.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1rem;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 2rem;
}

.step {
  padding: 0.5rem 1rem;
  background-color: #f0f0f0;
  border-radius: 20px;
  font-size: 0.9rem;
  color: #666;
}

.step.active {
  background-color: #1890ff;
  color: white;
}

.step-line {
  width: 60px;
  height: 2px;
  background-color: #ddd;
  margin: 0 1rem;
}

.loading {
  text-align: center;
  padding: 3rem;
  color: #666;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-message {
  text-align: center;
  padding: 3rem;
  background-color: #fff1f0;
  border-radius: 8px;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.error-text {
  color: #f5222d;
  margin-bottom: 1rem;
}

.retry-btn {
  padding: 0.5rem 1.5rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.checkout-content>div {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.checkout-content h2 {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1rem;
}

/* 订单商品样式 */
.item {
  display: flex;
  align-items: center;
  padding: 1rem 0;
  border-bottom: 1px solid #eee;
}

.item:last-child {
  border-bottom: none;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 1rem;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 1rem;
  color: #333;
  margin-bottom: 0.5rem;
}

.item-spec {
  font-size: 0.9rem;
  color: #666;
}

.item-price,
.item-quantity,
.item-total {
  text-align: center;
  margin: 0 1rem;
}

.item-total {
  font-weight: 600;
  color: #f5222d;
}

/* 地址样式 */
.no-address {
  text-align: center;
  padding: 2rem;
  color: #666;
}



.address-list {
  display: grid;
  gap: 1rem;
}

.address-item {
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #1890ff;
}

.address-item.active {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.address-info {
  margin-bottom: 1rem;
}

.contact {
  margin-bottom: 0.5rem;
}

.name {
  font-weight: 600;
  margin-right: 1rem;
}

.phone {
  color: #666;
}

.address-detail {
  color: #333;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 0.5rem;
}

.edit-btn,
.delete-btn {
  padding: 0.25rem 0.75rem;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
}

.delete-btn {
  color: #f5222d;
  border-color: #f5222d;
}

/* 支付方式样式 */
.payment-methods {
  display: grid;
  gap: 1rem;
}

.payment-method {
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.payment-method:hover {
  border-color: #1890ff;
}

.payment-method.active {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.method-icon {
  font-size: 1.5rem;
  margin-right: 1rem;
}

.method-name {
  font-weight: 600;
  margin-right: 1rem;
}

.method-desc {
  color: #666;
  font-size: 0.9rem;
}

/* 订单摘要样式 */
.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #eee;
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-item.total {
  font-weight: 600;
  font-size: 1.1rem;
  border-top: 2px solid #eee;
  padding-top: 1rem;
  margin-top: 1rem;
}

.total-amount {
  color: #f5222d;
  font-size: 1.2rem;
}

/* 提交按钮样式 */
.checkout-actions {
  text-align: center;
  padding: 2rem 0;
}

.submit-order-btn {
  padding: 1rem 3rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-order-btn:hover {
  background-color: #d32029;
}

.submit-order-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.debug-info {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 0.8rem;
}

.debug-info h4 {
  margin: 0 0 0.5rem 0;
  color: #666;
}

.debug-info pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
  color: #333;
}

@media (max-width: 768px) {
  .checkout-container {
    padding: 0 1rem;
  }

  .step-indicator {
    flex-direction: column;
    gap: 1rem;
  }

  .step-line {
    width: 2px;
    height: 20px;
  }

  .item {
    flex-wrap: wrap;
  }

  .item-info {
    flex: 1 0 100%;
    margin-bottom: 1rem;
  }

  .payment-method {
    flex-direction: column;
    text-align: center;
  }

  .method-icon,
  .method-name {
    margin-right: 0;
    margin-bottom: 0.5rem;
  }
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 1.5rem;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: 1.5rem;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.cancel-btn,
.confirm-btn {
  padding: 0.5rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
}

.confirm-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 地址选择样式 */
.no-addresses {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.selection-tip {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  padding: 1rem;
  margin-bottom: 1rem;
  text-align: center;
}

.selection-tip p {
  margin: 0;
  color: #52c41a;
  font-size: 0.9rem;
}

.address-selection {
  display: grid;
  gap: 1rem;
}

.address-option {
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.address-option:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.address-option.active {
  border-color: #1890ff;
  background-color: #f0f8ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.address-option.already-in-checkout {
  border-color: #52c41a;
  background-color: #f6ffed;
}

.address-content {
  margin-bottom: 0.5rem;
}

.address-status {
  text-align: right;
  font-size: 0.9rem;
}

.in-checkout {
  color: #52c41a;
  font-weight: 600;
}

.selected {
  color: #1890ff;
  font-weight: 600;
}

.available {
  color: #666;
}
</style>